package com.qk.management.web.filter;

import cn.hutool.core.util.ObjectUtil;
import com.qk.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
//@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    private static final String LOGIN_PATH = "/login";
    private static final String LOGIN_HEADER_NAME = "token";
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        String path = request.getRequestURI();
        boolean isLoginReq = ObjectUtil.equal(path, LOGIN_PATH);
        if (isLoginReq){
           chain.doFilter(request, response);
           return;
        }
        String header = request.getHeader(LOGIN_HEADER_NAME);
        if(ObjectUtil.isEmpty( header)){
            response.setStatus(401);
            return;
        }
        try {
            Claims claims = JwtUtil.parseToken(header);
            Object id = claims.get("id");
            log.info("用户id为{}",id);
            Object username = claims.get("username");
            log.info("用户名为{}",username);
            chain.doFilter(request, response);
            return;
        }catch (Exception e){
            response.setStatus(401);
            return;
        }


    }
}
